import json
import requests
import os
from openpyxl import Workbook, load_workbook
from urllib.parse import urlencode
#
# 饿了么系统
#
def main():
    # 确保 pic 文件夹存在
    if not os.path.exists("pic"):
        os.makedirs("pic")

    # 从 response.json 文件中读取 JSON 数据
    with open("response.json", "r", encoding="utf-8") as file:
        data = json.load(file)

    # 构造目标文件夹及文件路径
    folder_path = os.path.join(os.getcwd(), 'excel')
    file_path = os.path.join(folder_path, 'excel.xlsx')

    # 如果文件夹不存在则创建
    os.makedirs(folder_path, exist_ok=True)

    # 判断文件是否存在
    if os.path.isfile(file_path):
        wb = load_workbook(file_path)
        ws = wb.active
    else:
        wb = Workbook()
        ws = wb.active

    # 遍历 foods 列表
    for food in data["result"]["foods"]:
        name = food["name"]
        image_url = food["imageUrl"]
        image_url = urlencode(image_url, encoding='utf-8')
        # 清理文件名中的特殊字符
        safe_name = name.replace("【", "").replace("】", "").replace("/", "_").replace("\\", "_")
        # 获取下一空行行号（max_row 会返回最后一行有数据的行号，+1 就是下一行）
        next_row = ws.max_row + 1

        # 写入数据
        ws.cell(row=next_row, column=1, value=safe_name)  # A列
        ws.cell(row=next_row, column=2, value=image_url)  # B列

    # 保存文件
    wb.save(file_path)
    print("数据已保存到 excel.xlsx 文件中")

if __name__ == '__main__':
    main()